'use client';

import { useState } from 'react';
import { 
  Search, 
  Award,
  Users,
  Clock,
  ThumbsUp,
  ThumbsDown,
  Filter,
  CheckCircle2,
  XCircle,
  Eye
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { FadeIn } from '@/components/ui/motion';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { Textarea } from '@/components/ui/textarea';

// 模拟数据
const mockRewards = [
  {
    id: 1,
    studentId: '20230001',
    studentName: '张三',
    type: '奖励',
    reason: '数学竞赛一等奖',
    description: '在市级数学竞赛中获得一等奖，表现优异。',
    status: 'pending',
    date: '2024-03-15',
    submitter: '王老师',
    class: '三年级二班'
  },
  {
    id: 2,
    studentId: '20230002',
    studentName: '李四',
    type: '奖励',
    reason: '优秀班干部',
    description: '担任班长期间，工作认真负责，深受同学信任。',
    status: 'approved',
    date: '2024-03-14',
    submitter: '李老师',
    class: '三年级一班',
    approver: '张主任',
    approveDate: '2024-03-15',
    comment: '表现优异，同意表彰'
  },
  {
    id: 3,
    studentId: '20230003',
    studentName: '王五',
    type: '惩罚',
    reason: '课堂扰乱秩序',
    description: '上课期间多次讲话，影响课堂秩序。',
    status: 'rejected',
    date: '2024-03-13',
    submitter: '赵老师',
    class: '三年级三班',
    approver: '张主任',
    approveDate: '2024-03-14',
    comment: '建议先由班主任谈话教育'
  }
];

export default function RewardsApprovePage() {
  const { toast } = useToast();
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterType, setFilterType] = useState('all');
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedReward, setSelectedReward] = useState<any>(null);
  const [approveComment, setApproveComment] = useState('');
  
  // 处理审批操作
  const handleApprove = (approved: boolean) => {
    if (!approveComment) {
      toast({
        title: "请填写审批意见",
        description: "审批意见不能为空",
        variant: "destructive"
      });
      return;
    }
    
    toast({
      title: approved ? "审批通过" : "审批驳回",
      description: `已${approved ? '通过' : '驳回'}该${selectedReward.type}记录`,
    });
    
    setDetailDialogOpen(false);
    setApproveComment('');
  };
  
  // 查看详情
  const handleViewDetail = (reward: any) => {
    setSelectedReward(reward);
    setDetailDialogOpen(true);
    setApproveComment('');
  };
  
  // 过滤记录
  const filteredRewards = mockRewards.filter(reward => {
    const matchSearch = 
      reward.studentName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      reward.studentId.includes(searchTerm) ||
      reward.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
      reward.class.toLowerCase().includes(searchTerm.toLowerCase());
      
    const matchStatus = filterStatus === 'all' || reward.status === filterStatus;
    const matchType = filterType === 'all' || reward.type === filterType;
    
    return matchSearch && matchStatus && matchType;
  });

  // 统计数据
  const pendingCount = mockRewards.filter(r => r.status === 'pending').length;
  const approvedCount = mockRewards.filter(r => r.status === 'approved').length;
  const rejectedCount = mockRewards.filter(r => r.status === 'rejected').length;

  return (
    <FadeIn>
      <Toaster />
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">奖惩审批</h1>
          <div className="flex space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                type="search"
                placeholder="搜索学生、班级或记录..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="状态筛选" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="pending">待审批</SelectItem>
                <SelectItem value="approved">已通过</SelectItem>
                <SelectItem value="rejected">已驳回</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterType} onValueChange={setFilterType}>
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="类型筛选" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="奖励">奖励</SelectItem>
                <SelectItem value="惩罚">惩罚</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        
        {/* 统计卡片 */}
        <div className="mb-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <Award className="h-5 w-5 mr-2" />
                奖惩记录概览
              </CardTitle>
              <CardDescription>
                待处理和已处理的奖惩记录统计
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-yellow-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">待审批</p>
                      <p className="text-2xl font-bold text-yellow-600">{pendingCount}</p>
                    </div>
                    <div className="p-2 bg-yellow-100 rounded-full">
                      <Clock className="h-6 w-6 text-yellow-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">已通过</p>
                      <p className="text-2xl font-bold text-green-600">{approvedCount}</p>
                    </div>
                    <div className="p-2 bg-green-100 rounded-full">
                      <ThumbsUp className="h-6 w-6 text-green-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-red-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">已驳回</p>
                      <p className="text-2xl font-bold text-red-600">{rejectedCount}</p>
                    </div>
                    <div className="p-2 bg-red-100 rounded-full">
                      <ThumbsDown className="h-6 w-6 text-red-600" />
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
        
        {/* 记录列表 */}
        <div className="space-y-4">
          {filteredRewards.length > 0 ? (
            filteredRewards.map((reward) => (
              <Card key={reward.id}>
                <CardHeader className="pb-2">
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center space-x-2">
                        <CardTitle className="text-lg">{reward.studentName}</CardTitle>
                        <Badge className={`${
                          reward.type === '奖励' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                        }`}>
                          {reward.type}
                        </Badge>
                        <Badge className={`${
                          reward.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                          reward.status === 'approved' ? 'bg-green-100 text-green-800' :
                          'bg-red-100 text-red-800'
                        }`}>
                          {reward.status === 'pending' ? '待审批' :
                           reward.status === 'approved' ? '已通过' : '已驳回'}
                        </Badge>
                      </div>
                      <CardDescription>
                        学号: {reward.studentId} · 班级: {reward.class} · 提交时间: {reward.date}
                      </CardDescription>
                    </div>
                    <div className="flex space-x-2">
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="h-8"
                        onClick={() => handleViewDetail(reward)}
                      >
                        <Eye className="h-4 w-4 mr-1" />
                        <span>查看详情</span>
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div>
                      <span className="font-medium">原因：</span>
                      <span className="text-gray-700">{reward.reason}</span>
                    </div>
                    <div>
                      <span className="font-medium">提交人：</span>
                      <span className="text-gray-700">{reward.submitter}</span>
                    </div>
                    {reward.status !== 'pending' && (
                      <div>
                        <span className="font-medium">审批意见：</span>
                        <span className="text-gray-700">{reward.comment}</span>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))
          ) : (
            <div className="text-center py-8">
              <p className="text-gray-500">暂无奖惩记录</p>
            </div>
          )}
        </div>
        
        {/* 详情对话框 */}
        <Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              <DialogTitle>奖惩记录详情</DialogTitle>
              <DialogDescription>
                查看详细信息并进行审批
              </DialogDescription>
            </DialogHeader>
            {selectedReward && (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>学生姓名</Label>
                    <div className="mt-1">{selectedReward.studentName}</div>
                  </div>
                  <div>
                    <Label>学号</Label>
                    <div className="mt-1">{selectedReward.studentId}</div>
                  </div>
                  <div>
                    <Label>班级</Label>
                    <div className="mt-1">{selectedReward.class}</div>
                  </div>
                  <div>
                    <Label>提交教师</Label>
                    <div className="mt-1">{selectedReward.submitter}</div>
                  </div>
                  <div>
                    <Label>记录类型</Label>
                    <div className="mt-1">{selectedReward.type}</div>
                  </div>
                  <div>
                    <Label>提交时间</Label>
                    <div className="mt-1">{selectedReward.date}</div>
                  </div>
                </div>
                <div>
                  <Label>具体原因</Label>
                  <div className="mt-1">{selectedReward.reason}</div>
                </div>
                <div>
                  <Label>详细说明</Label>
                  <div className="mt-1">{selectedReward.description}</div>
                </div>
                {selectedReward.status === 'pending' && (
                  <div>
                    <Label htmlFor="comment">审批意见</Label>
                    <Textarea
                      id="comment"
                      className="mt-1"
                      placeholder="请输入审批意见..."
                      value={approveComment}
                      onChange={(e) => setApproveComment(e.target.value)}
                    />
                  </div>
                )}
              </div>
            )}
            <DialogFooter>
              {selectedReward?.status === 'pending' ? (
                <>
                  <Button variant="outline" onClick={() => handleApprove(false)}>
                    <XCircle className="h-4 w-4 mr-1" />
                    驳回
                  </Button>
                  <Button onClick={() => handleApprove(true)}>
                    <CheckCircle2 className="h-4 w-4 mr-1" />
                    通过
                  </Button>
                </>
              ) : (
                <Button variant="outline" onClick={() => setDetailDialogOpen(false)}>
                  关闭
                </Button>
              )}
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </FadeIn>
  );
}
